package com.example.studyktdemo.ui.fragment

import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.studyktdemo.adapter.FocusOnAdapter
import com.example.studyktdemo.bean.FocusOnBean
import com.example.studyktdemo.databinding.FragmentFocusOnBinding
import com.example.studyktdemo.viewmodel.FocusOnViewModel

class FocusOnFragment : Fragment() {

    private lateinit var binding: FragmentFocusOnBinding
    private lateinit var viewModel: FocusOnViewModel
    private var adapter: FocusOnAdapter? = null

    private val linearLayoutManager by lazy {
        LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
    }

    companion object {
        fun getInstance(): FocusOnFragment {
            val instance = FocusOnFragment()

            return instance
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentFocusOnBinding.inflate(layoutInflater)

        viewModel = ViewModelProvider(
            this,
            ViewModelProvider.NewInstanceFactory()
        )[FocusOnViewModel::class.java]

        initView()
        initObserver()

        viewModel.queryFocusInfo()
        binding.focusStatus.showLoading()
        return binding.root

    }

    private fun initView() {
        adapter = FocusOnAdapter()

        binding.focusRv.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                outRect.bottom = 30
            }
        })

        binding.focusRv.adapter = adapter
        binding.focusRv.layoutManager = linearLayoutManager
    }

    private fun initObserver() {
        viewModel.getFocusMutableLiveData()?.observe(this, object : Observer<FocusOnBean> {
            override fun onChanged(focusOnData: FocusOnBean?) {
                if (focusOnData != null) {
                    binding.focusStatus.showContent()
                    adapter?.setData(focusOnData)
                } else {
                    binding.focusStatus.showEmpty()
                }
            }
        })
    }
}